<?php


function app_login($username, $password)
{
	
   //检查用户是否存在
   $sql = "SELECT user_id,key_salt FROM " . $GLOBALS['db']->table("users") .
    " WHERE user_phone='$username'";

   $result = $GLOBALS['db']->getRow($sql);

	if($result){
        if(empty($result['key_salt']))
        {
			$sql = "SELECT user_id FROM " . $GLOBALS['db']->table("users") .
				 " WHERE user_phone='$username' AND password = '" . $password ."'";

			$user_exist = $GLOBALS['db']->getOne($sql);

			if(!empty($user_exist)){
				
				$key_salt = rand(1,9999);
				$sql = 'UPDATE ' . $GLOBALS['db']->table("users") ."SET `password`='".md5($password. $key_salt).
					 "',`key_salt`='". $key_salt. "' WHERE user_id = '" . $user_exist . "'";
				$GLOBALS['db']->query($sql);
					
				return $user_exist;
			}else{
				return false;
			}
				
		}else{

				
			$sql = "SELECT user_id FROM " . $GLOBALS['db']->table("users") .
				 " WHERE user_phone='$username' AND password = '" .
				  md5($password. $result['key_salt'])."'";
            $user_exist = $GLOBALS['db']->getOne($sql);
			
			if(!empty($user_exist)){
				
				$where = ' user_id = '.$user_exist;
				$up_info['last_login']	 = time();
				$GLOBALS['db']->autoExecute($GLOBALS['db']->table('users'), $up_info, 'UPDATA',$where);
					
				return $user_exist;
				
			}else{
				return false;
			}
			
		}
			
	}else{
		return false;	
	}

}


function app_register($input_data)
{
	$res_msg=array('code'=>'','info'=>'');
	
	//====================验证账号是否重复=============================
	$sql = 'SELECT count(*) FROM ' .$GLOBALS['db']->table('users').
	' WHERE user_phone ="'.$input_data['user_phone'].'"';
    $res_count = $GLOBALS['db']->getOne($sql);	
    if($res_count>0){
		$res_msg=array('code'=>0,'info'=>"注册账号[".$input_data['user_phone']."]已存在");
		return $res_msg;
    }
	

	$is_verify = false;
	if($is_verify == true){
	//===================验证短信码====================================
	$sql = 'SELECT record_code FROM ' .$GLOBALS['db']->table('validate_record').
			' WHERE record_key ="'.$input_data['user_phone'].'"';
    $res_record = $GLOBALS['db']->getOne($sql);
	
    if(!empty($res_record)){
		if($res_record != $input_data['code']){
			
			$res_msg=array('code'=>0,'info'=>"短信验证码不正确");
			return $res_msg;
		}
    }else{

		$res_msg=array('code'=>0,'info'=>"验证码信息不存在");
		return $res_msg;
	}
	//===============================================================
	}
	
	//添加
	$user_info['password']	 = $input_data['password'];
	$user_info['user_phone'] = $input_data['user_phone'];//主账号
	
	$user_info['user_rank']	 = 1;		// 会员等级：普通用户
	$user_info['reg_time']	 = time();	// 注册时间
	$user_info['status']	 = 1; 		// 用户账号状态 1 可用 2不可用
	$user_info['sex']		 = 0;
	$user_info['is_validated'] = 2;
	
	$res = $GLOBALS['db']->autoExecute($GLOBALS['db']->table('users'), $user_info, 'INSERT');
	$res_id = $GLOBALS['db']->insert_id();
	
	if($res){

		$res_msg = array('code'=>1,'info'=>'用户['.$input_data['user_phone'].']注册成功');
	}else{	
		$res_msg = array('code'=>0,'info'=>"用户注册失败");
	}
	
	return $res_msg;
}




function get_userInfo($user_id=0)
{
	$user_info = array();
	$sql="SELECT * FROM " .$GLOBALS['db']->table('users')." WHERE user_id='$user_id' LIMIT 1";
	$res = $GLOBALS['db']->getRow($sql);
	
	$user_sex = array('未知','男','女');
	$usericon = GZ_Api::get_url('/Mapi/public/images/usericon.png');
	$user_info['user_id']		 = $res['user_id'];
	$user_info['user_phone']	 = $res['user_phone'];//用户账号
	$user_info['user_name']		 = empty($res['user_name'])?'':$res['user_name'];
	$user_info['user_nickname']	 = empty($res['nickname'])?'':$res['nickname'];
	$user_info['user_money']	 = empty($res['user_money'])?'0.00':$res['user_money'];
	$user_info['user_integral']	 = empty($res['user_integral'])?'0':$res['user_integral'];
	
	$user_info['user_rank']		 = $res['user_rank'];
	switch ($res['user_rank']) {
		case '1':
			$user_info['rank_name']='普通用户';
			break;
		case '2':
			$user_info['rank_name']='爱心用户';
			break;
		case '3':
			$user_info['rank_name']='医师';
			break;
		default:
			break;
	}
	
	$user_info['user_sex']		 = $res['sex'];
	$user_info['user_sex_des']	 = $user_sex[$res['sex']];
	$user_info['user_headimg']	 = empty($res['headimg'])?$usericon:GZ_Api::get_url($res['headimg']);
	$user_info['birthday']		 = $res['birthday'];
	$user_info['user_age']		 = empty($res['age'])?'':$res['age'];
	$user_info['is_validated']	 = $res['is_validated']==2?0:$res['is_validated'];
	$user_info['status']		 = $res['status'];
	$user_info['key_salt']		 = $res['key_salt'];	
	return $user_info;
}

/**
 * 更新用户TOKEN
 *
 * @access  public
 * @param   array $up_info
 */
function update_token($access_id,$up_info){
	
	$user_id	 = $up_info['user_id'];
	$user_name	 = $up_info['user_name'];
	$up_token	 = md5($access_id.$up_info['key_salt']);
	
	$sql = 'select token from '.$GLOBALS['db']->table('users_token').' where user_id ='.$user_id.' LIMIT 1';
	$data = $GLOBALS['db']->getOne($sql);
	
	if(!empty($data))
	{
		$sql="UPDATE ".$GLOBALS['db']->table('users_token')." SET `token`='".$up_token."' WHERE `user_id`=".$user_id;
		
	}else{
		
		$expiry = time()+2592000;//一个月
		
		$sql = "INSERT INTO " . $GLOBALS['db']->table('users_token') .
		 " (token, expiry,user_id,user_name) VALUES ('" . $up_token . "',". $expiry .",".$user_id.",'".$user_name."')";
	}
	
	$GLOBALS['db']->query($sql);
	
	return $access_id;
}

function get_all_token(){
	$sql = 'SELECT user_id,user_name,token FROM '. $GLOBALS['db']->table("users_token").' WHERE 1';
	$res = $GLOBALS['db']->getAll($sql);
	return $res;
}

/**上传图片
 * @param $dir_type <1-头像，2-实名认证>
 * @author leiying
 */
function upload_imgae($dir_type){
    switch($dir_type){
        case '1':
            $type = "Headimg";//文件目录
            break;
        case '2':
            $type = "Auth";//文件目录
            break;
         case '3':
            $type = "Rescue";//文件目录
            break;   
        default:
            GZ_Api::message("请选择合法图片类型",2);
            break;
    }

    if(empty($_FILES['img']['tmp_name']))
    {
        GZ_Api::message("请选择一张图片",0);
    }

    $http_host =  "http://".$_SERVER['HTTP_HOST'];

    $img_name = random_filename().".jpg";

    $file_date = date("Y-m-d");

    //不存在则创建文件
    $dir_path = $_SERVER['DOCUMENT_ROOT']."/Uploads/".$type."/".$file_date."/";
    if(!file_exists($dir_path)){
        mkdir($dir_path,0777,true);
    }

    $img_path = "/Uploads/".$type."/".$file_date."/".$img_name;

    $image_path = EC_PATH.'/Uploads/'.$type.'/'.$file_date."/"; // 文件保存路径
    mkdirs($image_path);// 生成的文件夹

    $image_path = $image_path.$img_name;

    if(empty($_FILES['img']['tmp_name']))
    {
        GZ_Api::message("文件为空",2);
    }


    chmod($_FILES['img']['tmp_name'],0777);

    if( copy( $_FILES['img']['tmp_name'],$image_path) == 1)
    {

        GZ_Api::outPut(array("img_url"=>$img_path));
    }
    else
    {
        GZ_Api::message("上传错误",2);
    }

}

function random_filename()
{
    $str = '';
    for($i = 0; $i < 9; $i++)
    {
        $str .= mt_rand(0, 9);
    }

    return gmtime() . $str;
}

function mkdirs($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
    if (!mkdirs(dirname($dir), $mode)) return FALSE;
    return @mkdir($dir, $mode);
}

?>